<template>
  <view class="container">
    <!-- 商品信息 -->
    <view class="goods-section">
      <tui-list-cell :hover="false">
        <view class="goods-info">
          <image :src="orderItem.picUrl" class="goods-image" mode="aspectFill"></image>
          <view class="goods-details">
            <view class="goods-name">{{ orderItem.spuName }}</view>
            <view class="goods-specs">
              <text v-for="property in orderItem.properties" :key="property.propertyId">
                {{ property.propertyName }}: {{ property.valueName }}
              </text>
            </view>
            <view class="goods-price">￥{{ fen2yuan(orderItem.payPrice) }}</view>
          </view>
        </view>
      </tui-list-cell>
    </view>

    <!-- 评分区域 -->
    <view class="rating-section">
      <tui-list-cell :hover="false">
        <view class="rating-item">
          <text class="rating-label">商品描述</text>
          <tui-rate :current="descriptionScores" @change="onDescriptionScoreChange"></tui-rate>
        </view>
      </tui-list-cell>
      <tui-list-cell :hover="false">
        <view class="rating-item">
          <text class="rating-label">服务态度</text>
          <tui-rate :current="benefitScores" @change="onBenefitScoreChange"></tui-rate>
        </view>
      </tui-list-cell>
    </view>

    <!-- 评价内容 -->
    <view class="content-section">
      <tui-list-cell :hover="false" padding="0">
        <textarea 
          v-model="commentContent" 
          class="comment-textarea" 
          placeholder="说说商品怎么样，给其他买家参考一下吧..." 
          maxlength="200"
          :show-count="true"
        ></textarea>
      </tui-list-cell>
    </view>

    <!-- 图片上传 -->
    <view class="upload-section">
      <tui-list-cell :hover="false">
        <view class="upload-title">
          <text>添加图片</text>
          <text class="upload-tip">最多上传9张图片</text>
        </view>
        <view class="upload-grid">
          <view 
            v-for="(image, index) in uploadedImages" 
            :key="index"
            class="upload-item"
          >
            <image :src="image" class="upload-image" mode="aspectFill"></image>
            <view class="delete-btn" @click="removeImage(index)">
              <tui-icon name="close" size="20" color="#fff"></tui-icon>
            </view>
          </view>
          <view 
            v-if="uploadedImages.length < 9" 
            class="upload-item upload-add"
            @click="chooseImage"
          >
            <tui-icon name="plus" size="40" color="#ccc"></tui-icon>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
      </tui-list-cell>
    </view>

    <!-- 匿名评价 -->
    <view class="anonymous-section">
      <tui-list-cell :hover="false">
        <view class="anonymous-item">
          <checkbox-group @change="onAnonymousChange">
            <label class="checkbox-label">
              <checkbox :checked="isAnonymous" color="#EB0909"></checkbox>
              <text class="checkbox-text">匿名评价</text>
            </label>
          </checkbox-group>
        </view>
      </tui-list-cell>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <tui-button 
        type="danger" 
        height="88rpx" 
        shape="circle"
        :disabled="!canSubmit"
        @click="submitComment"
      >
        提交评价
      </tui-button>
    </view>

    <!-- 加载遮罩 -->
    <view v-if="loading" class="loading-mask">
      <tui-loading size="40" color="#fff"></tui-loading>
      <text class="loading-text">提交中...</text>
    </view>
  </view>
</template>

<script>
import tuiButton from '@/components/thorui/tui-button/tui-button.vue'
import tuiRate from '@/components/thorui/tui-rate/tui-rate.vue'
import tuiListCell from '@/components/thorui/tui-list-cell/tui-list-cell.vue'
import tuiIcon from '@/components/thorui/tui-icon/tui-icon.vue'
import tuiLoading from '@/components/thorui/tui-loading/tui-loading.vue'

export default {
  components: {
    tuiButton,
    tuiRate,
    tuiListCell,
    tuiIcon,
    tuiLoading
  },
  data() {
    return {
      orderItem: {}, // 订单项信息
      descriptionScores: 5, // 描述评分
      benefitScores: 5, // 服务评分
      commentContent: '', // 评价内容
      uploadedImages: [], // 上传的图片
      isAnonymous: false, // 是否匿名
      loading: false, // 提交状态
      orderItemId: null // 订单项ID
    }
  },
  computed: {
    // 是否可以提交
    canSubmit() {
      return this.commentContent.trim().length > 0 && 
             this.descriptionScores > 0 && 
             this.benefitScores > 0 &&
             !this.loading;
    }
  },
  onLoad(options) {
    if (options.orderItemId) {
      this.orderItemId = options.orderItemId;
      this.loadOrderItem();
    } else if (options.orderId) {
      // 如果传入的是订单ID，需要先获取订单项
      this.loadOrderItemsByOrderId(options.orderId);
    }
  },
  methods: {
    // 分转元函数
    fen2yuan(price) {
      return (Number(price) / 100).toFixed(2);
    },

    // 加载订单项详情
    loadOrderItem() {
      if (!this.orderItemId) return;
      
      this.$api
        .getOrderItem(this.orderItemId)
        .then((res) => {
          if (res.code === 0) {
            this.orderItem = res.data;
          } else {
            uni.showToast({
              title: res.msg || '加载商品信息失败',
              icon: 'none'
            });
          }
        })
        .catch(() => {
          uni.showToast({
            title: '加载商品信息失败',
            icon: 'none'
          });
        });
    },

    // 根据订单ID加载订单项（如果有多个商品，取第一个未评价的）
    loadOrderItemsByOrderId(orderId) {
      this.$api
        .req(`/trade/order/get-detail`, { id: orderId }, 'GET')
        .then((res) => {
          if (res.code === 0 && res.data.items && res.data.items.length > 0) {
            // 找到第一个未评价的商品
            const uncommentedItem = res.data.items.find(item => !item.commentStatus);
            if (uncommentedItem) {
              this.orderItem = uncommentedItem;
              this.orderItemId = uncommentedItem.id;
            } else {
              uni.showToast({
                title: '该订单已全部评价完成',
                icon: 'none'
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          }
        })
        .catch(() => {
          uni.showToast({
            title: '加载订单信息失败',
            icon: 'none'
          });
        });
    },

    // 描述评分变化
    onDescriptionScoreChange(e) {
      this.descriptionScores = e.index;
    },

    // 服务评分变化
    onBenefitScoreChange(e) {
      this.benefitScores = e.index;
    },

    // 匿名评价变化
    onAnonymousChange(e) {
      this.isAnonymous = e.detail.value.length > 0;
    },

    // 选择图片
    chooseImage() {
      const remainingCount = 9 - this.uploadedImages.length;
      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 这里应该上传到服务器，暂时使用本地路径
          this.uploadedImages.push(...res.tempFilePaths);
        },
        fail: () => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 删除图片
    removeImage(index) {
      this.uploadedImages.splice(index, 1);
    },

    // 提交评价
    submitComment() {
      if (!this.canSubmit) return;

      // 验证评价内容
      if (this.commentContent.trim().length < 5) {
        uni.showToast({
          title: '评价内容至少5个字符',
          icon: 'none'
        });
        return;
      }

      this.loading = true;

      const commentData = {
        orderItemId: this.orderItemId,
        anonymous: this.isAnonymous,
        descriptionScores: this.descriptionScores,
        benefitScores: this.benefitScores,
        content: this.commentContent.trim(),
        picUrls: this.uploadedImages // 这里应该是上传后的URL数组
      };

      this.$api
        .createOrderItemComment(commentData)
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              title: '评价提交成功',
              icon: 'success'
            });
            
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.msg || '评价提交失败',
              icon: 'none'
            });
          }
        })
        .catch(() => {
          uni.showToast({
            title: '评价提交失败，请重试',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.goods-section {
  margin-bottom: 20rpx;
}

.goods-info {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.goods-details {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-specs {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.goods-price {
  font-size: 26rpx;
  color: #EB0909;
  font-weight: 600;
}

.rating-section {
  margin-bottom: 20rpx;
}

.rating-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
}

.rating-label {
  font-size: 28rpx;
  color: #333;
}

.content-section {
  margin-bottom: 20rpx;
}

.comment-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.5;
  background: #fff;
  border: none;
  box-sizing: border-box;
}

.upload-section {
  margin-bottom: 20rpx;
}

.upload-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  text:first-child {
    font-size: 28rpx;
    color: #333;
  }
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
}

.upload-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-item {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  position: relative;
  overflow: hidden;
}

.upload-image {
  width: 100%;
  height: 100%;
}

.upload-add {
  border: 2rpx dashed #ddd;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.anonymous-section {
  margin-bottom: 40rpx;
}

.anonymous-item {
  padding: 20rpx 0;
}

.checkbox-label {
  display: flex;
  align-items: center;
}

.checkbox-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-text {
  color: #fff;
  font-size: 28rpx;
  margin-top: 20rpx;
}

/* 复选框样式 */
::v-deep .uni-checkbox-input {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  background: #fff;
}

::v-deep .uni-checkbox-input.uni-checkbox-input-checked {
  background: #EB0909;
  border-color: #EB0909;
}

::v-deep .uni-checkbox-input.uni-checkbox-input-checked::before {
  color: #fff;
  font-size: 24rpx;
}
</style>